DEFINT A-Z

TYPE CrdMetaT
  MAGIC AS STRING*3
  COUNT AS INTEGER
END TYPE
TYPE CrdHeaderT
  RES AS STRING*6
  OFFSET AS LONG
  FLAG AS STRING*1
  TEXT AS STRING*41
END TYPE
TYPE CrdContentT
  FLAG AS INTEGER
  SIZE AS INTEGER
  TEXT AS STRING*4096
END TYPE

DIM CRDMETA AS CrdMetaT,CRDHDR AS CrdHeaderT,CRDCONTENT AS CrdContentT

PRINT "*** Windows Cardfile Format Converter ***":PRINT ""
ACT=0:WHILE ACT<>1 AND ACT <>2
INPUT "Select function (1:CRD->TXT 2:TXT->CRD): ",ACT
WEND
IF ACT=2 THEN
  INPUT "Source file:",F$
  OPEN F$ FOR INPUT ACCESS READ AS #1
  INPUT "Destination .CRD file:",FO$
  OPEN FO$ FOR BINARY AS #2
  CRDMETA.MAGIC="MGC"
  CRDMETA.COUNT=0
  WHILE NOT EOF(1)
    LINE INPUT#1,L$
    IF INSTR(L$,".TITLE:")=1 THEN
      IF NOT EOF(1) THEN LINE INPUT#1,L2$
      IF INSTR(L2$,".TEXT:")=1 THEN
        CRDHDR.TEXT=MID$(RTRIM$(L$),8)+CHR$(0)
        CRDHDR.FLAG=CHR$(0)
        PUT #2,6+CRDMETA.COUNT*52,CRDHDR
        CRDMETA.COUNT=CRDMETA.COUNT+1
      END IF
    END IF
  WEND
  PUT #2,1,CRDMETA
  CLOSE #1:OPEN F$ FOR INPUT ACCESS READ AS #1
  IDX=0
  OFFSET=5+CRDMETA.COUNT*52
  WHILE NOT EOF(1)
    LINE INPUT#1,L$
    IF INSTR(L$,".TITLE:")=1 THEN
      IF NOT EOF(1) THEN LINE INPUT#1,L2$
      IF INSTR(L2$,".TEXT:")=1 THEN
        COUNT=VAL(MID$(L2$,7))
        CONTENT$=""
        WHILE COUNT>0 AND NOT EOF(1)
          LINE INPUT#1,L$
          CONTENT$=CONTENT$+RTRIM$(L$)
          IF COUNT>1 THEN CONTENT$=CONTENT$+CHR$(&H0D)+CHR$(&H0A)
          COUNT=COUNT-1
        WEND
        WD$=MKL$(OFFSET)
        PUT #2,6+IDX*52+6,WD$:IDX=IDX+1
        WD$=MKI$(0)+MKI$(LEN(CONTENT$))+CONTENT$
        PUT #2,OFFSET+1,WD$
        OFFSET=OFFSET+LEN(WD$)
      END IF
    END IF
  WEND
ELSE
  INPUT "Source .CRD file:",F$
  OPEN F$ FOR BINARY ACCESS READ AS #1
  GET #1,1,CRDMETA
  IF CRDMETA.MAGIC<>"MGC" THEN CLOSE #1:PRINT "Unsupported file format.":END
  INPUT "Destination file:",F$
  OPEN F$ FOR OUTPUT AS #2
  FOR I=0 TO CRDMETA.COUNT-1
    GET #1,6+I*52,CRDHDR
    PRINT#2,".TITLE:";MID$(CRDHDR.TEXT,1,INSTR(CRDHDR.TEXT,CHR$(0))-1)
    GET #1,CRDHDR.OFFSET+1,CRDCONTENT
    TEXT$=MID$(CRDCONTENT.TEXT,1,CRDCONTENT.SIZE)
    PRINT#2,".TEXT:";LTRIM$(RTRIM$(STR$(COUNTLINES(TEXT$))))
    PRINT#2,TEXT$
    PRINT#2,""
  NEXT I
END IF

PRINT "Conversion finished."
CLOSE #2
CLOSE #1

END

FUNCTION COUNTLINES(S AS STRING)
  STATIC C,P
  C=1:P=INSTR(1,S,CHR$(&H0A))
  WHILE P>0
    C=C+1
    P=INSTR(P+1,S,CHR$(&H0A))
  WEND
  COUNTLINES=C
END FUNCTION

